package com.tledu.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 测试服务端
 */
public class TestServer {
    public static void main(String[] args) throws IOException {
        // 查看本地ip
        //      本机ip： localhost / 127.0.0.1 (代表本地计算机)
        //      局域网ip: 命令行里执行 ipconfig 查看的局域网ip
        // 1. 创建Socket服务器,绑定ip（本机ip）,指定了服务的端口号
        ServerSocket serverSocket = new ServerSocket(8888);
       while (true){
           // 2. 调用了accept方法，开始监听，等待客户端连接
           Socket socket = serverSocket.accept();
           // 3. 获取输入流，并读取客户端的信息
           System.out.println(socket.getRemoteSocketAddress());
           InputStream in = socket.getInputStream();
           // 字节流转换成字符流
           InputStreamReader reader = new InputStreamReader(in);
           // 增加缓冲流
           BufferedReader bufferedReader = new BufferedReader(reader);
           while (true) {
               String line = bufferedReader.readLine();
               if (line == null) {
                   break;
               }
               System.out.print(line);
           }
           bufferedReader.close();
       }
    }
}
